import 'dart:typed_data';
import 'package:dio/dio.dart' as dio;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../services/userServices.dart';
import 'package:image_picker/image_picker.dart';
import '../../../services/httpsClient.dart';
import '../../../services/messageUtil.dart';

class UserController extends GetxController {
  //TODO: Implement UserController

  bool isLoading = true; //请求防抖控制
  HttpsClient httpsClient = HttpsClient();
  final userData = UserServices.getUserDataSync();

  final TextEditingController editUserNameController = TextEditingController();
  final TextEditingController editPhoneController = TextEditingController();
  final TextEditingController editPasswordController = TextEditingController();

  // 头像路径
  RxString avatarUrl = ''.obs;
  RxString avatarPath = ''.obs;
  @override
  void onInit() {
    super.onInit();
    //编辑用户
    editUserNameController.text = userData['name'];
    editPhoneController.text = userData['phone'];
    avatarUrl.value = userData['head_img'];
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  // 选择图片方法
  Future<void> pickImage() async {
    try {
      final picker = ImagePicker();
      final pickedFile = await picker.pickImage(source: ImageSource.gallery);

      if (pickedFile != null) {
        // 读取图片字节
        final bytes = await pickedFile.readAsBytes();
        // 显示本地选择的图片
        avatarUrl.value = pickedFile.path;

        // 开始上传
        uploadImage(bytes, pickedFile.name);
      }
    } catch (e) {
      Get.snackbar('错误', '头像上传失败');
    }
  }

  // 上传图片到服务器
  void uploadImage(Uint8List bytes, String filename) async {
    // 创建MultipartFile
    final multipartFile = dio.MultipartFile.fromBytes(
      bytes,
      filename: filename,
    );
    dio.FormData formData = dio.FormData.fromMap({
        'file': multipartFile,
      });
    var response = await httpsClient.postFromData("v1/user/upload",data: formData,);
    if (response != null) {
      if (response.data['code'] == 0) {
        MessageUtil.showSuccess(
          message: "上传成功",
          config: MessageUtilConfig(
            duration: const Duration(seconds: 1),
            indicatorColor: Colors.green,
          ),
        );
        // 上传成功后，更新用户头像
        avatarUrl.value = response.data['data']['url'];
        avatarPath.value = response.data['data']['path'];
        update();
      } else {
        MessageUtil.showError(message: response.data["message"]);
      }
    } else {
      MessageUtil.showError(message: "网络异常");
    }
  }

  // 提交编辑用户表单
  void submitEditUserForm() async {
    if (isLoading) {
      isLoading = false;
      var response = await httpsClient.post(
        "v1/user/edit",
        data: {
          "name": editUserNameController.text,
          "phone": editPhoneController.text,
          "password": editPasswordController.text,
          "head_img": avatarPath.value,
        },
      );

      if (response != null) {
        if (response.data['code'] == 0) {
          await UserServices.saveUserData(response.data["data"]);
          MessageUtil.showSuccess(
            message: "更新成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );
          
        await UserServices.clearUserData();
        Get.offAllNamed("/login");
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
    }
  }

  
  //退出登录
  logout() async {
    await UserServices.clearUserData();
    Get.toNamed("/login");
  }

}
